﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using SzlsRobots.Dtos;
using SzlsRobots.Models;

namespace SzlsRobots.Controllers
{
    [DynamicApiController]
    public class RobotsDataController
    {
        private readonly ILogger<RobotsDataController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public RobotsDataController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        //[HttpPost]
        //public async Task<IActionResult> Init()
        //{
        //    db.CodeFirst.InitTables<Project>();
        //    await db.Insertable(new Project { Id = 0, PNumber = "xxxxxx", INumber = "xxxx", Status = "Working" }).ExecuteCommandAsync();
        //    await db.Insertable(new Project { Id = 0, PNumber = "xxxxxx", INumber = "xxxx", Status = "Finish" }).ExecuteCommandAsync();
        //    return new JsonResult(new RESTfulResult<object>
        //    {
        //        StatusCode = 200,
        //        Succeeded = true,
        //        Data = "创建表成功",
        //        Errors = null,
        //        Extras = UnifyContext.Take(),
        //        Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
        //    });
        //}

        /// <summary>
        /// 工程数据列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] ProjectSearchFormDto psfd)
        {
            List<Project> projects = await db.Queryable<Project>()
                    .WhereIF(!string.IsNullOrEmpty(psfd.PNumber), p => p.PNumber == psfd.PNumber)
                    .WhereIF(!string.IsNullOrEmpty(psfd.INumber), p => p.INumber == psfd.INumber)
                    .WhereIF(psfd.BeginTime != DateTime.MinValue, p => p.Created.Date >= psfd.BeginTime.Date)
                    .WhereIF(psfd.EndTime != DateTime.MinValue, p => p.Created.Date <= psfd.EndTime.Date)
                    //.OrderBy(p => p.Id, OrderByType.Desc)
                    .ToListAsync();
            
            var data = projects.GroupBy(p => p.PNumber).Select(gp => new {
                PNumber = gp.Key,
                //Status = gp.FirstOrDefault().Status,
                Status = gp.LastOrDefault().Status
            });
            
            //// 如果工程编号为空，分组查询指定日期下所有工程
            //if (string.IsNullOrEmpty(psfd.PNumber))
            //{
            //    List<string> pNumbers = await db.Queryable<Project>()
            //        .GroupBy(p => p.PNumber)
            //        .Where(p => p.Created.Date >= psfd.BeginTime.Date)
            //        .Where(p => p.Created.Date <= psfd.EndTime.Date)
            //        .Select(p => p.PNumber)
            //        .ToListAsync();
            //    data = await db.Queryable<Project>()
            //        .Where(p => pNumbers.Contains(p.PNumber))
            //        .ToListAsync();
            //}
            //else {
            //    data = await db.Queryable<Project>()
            //        .Where(p => p.PNumber == psfd.PNumber)
            //        .WhereIF(!string.IsNullOrEmpty(psfd.INumber), p => p.INumber == psfd.INumber)
            //        .Where(p => p.Created.Date >= psfd.BeginTime.Date)
            //        .Where(p => p.Created.Date <= psfd.EndTime.Date)
            //        .ToListAsync();
            //}
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = !string.IsNullOrEmpty(psfd.PNumber) || !string.IsNullOrEmpty(psfd.INumber) ? projects : data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 保存工程数据
        /// </summary>
        /// <param name="psfd">参照下方Schema: ProjectSaveFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] ProjectSaveFormDto psfd)
        {
            await db.Insertable<Project>(psfd.Adapt<Project>()).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
